<?php

using('Library.Widgets.Form');
using('Library.Widgets.RecordSet');

class Module_Admin_articles extends Admin_IModule
{
    var $_Name  = 'articles';
    var $_Title = 'News';
    
    /**#@+
     * Required Core Objects
     *
     * These are references to the core objects required by this
     * class.
     *
     * @access private
     * @var    object
     */
    var $_Error;
    var $_Profiler;
    var $_DAL;
    var $_Model;
    /**#@-*/

    function __construct()
    {
        // Get references to required objects
        $this->_Error     = &Vault::Get('Debug_Error');
        $this->_Profiler  = &Vault::Get('Debug_Profiling');
        $this->_DAL       = &Vault::Get('DAL');
        $this->_Model     = &Vault::Get('Model');

        // Register Article Specific Actions
        $this->RegisterAction(array('article'),           'Articles', 'ManageArticles_List');
        $this->RegisterAction(array('article', 'create'), 'Create',          'ManageArticles_Create');
        $this->RegisterAction(array('article', 'modify'), 'Modify',          'ManageArticles_Modify');
        $this->RegisterAction(array('article', 'delete'), 'Delete',          'ManageArticles_Delete');
        
        // Register Category Specific Actions
        $this->RegisterAction(array('category'),           'Categories', 'ManageCategories_List');
        $this->RegisterAction(array('category', 'create'), 'Create',     'ManageCategories_Create');
        $this->RegisterAction(array('category', 'modify'), 'Modify',     'ManageCategories_Modify');
        $this->RegisterAction(array('category', 'delete'), 'Delete',     'ManageCategories_Delete');        
        
        // Call Admin_IModule constructor (we call it last so it has access to the actions array)
        parent::__construct();        
    }

    /*
     * Action Methods
     */
    
    function ManageArticles_List()
    {
    	/*
    	 * Generate List Articles Recordset
    	 */

    	$recordset = new RecordSet($this->GetAction('article'), 'articles', 'Articles [Manage]', 'newsarticle');
    	
    	// Recordset Actions
    	$recordset->AddAction('create', 'Create', array(&$this, 'ManageArticles_Create'));
    	$recordset->AddAction('delete', 'Delete', array(&$this, 'ManageArticles_Delete'));    	
    	
    	// Recordset Filters
    	$recordset->AddFilter('cid', 'Category', 'newscategory', 'id', 'title');    	
    	
    	// Recordset Fields
    	$recordset->AddField('id', '#', 30);
    	$recordset->AddField('u_display_name', 'Author', 100);    	
    	$recordset->AddField('c_title', 'Category', 100);     	
    	$recordset->AddField('n_title', 'Title', false, array(&$this, '_RecordSet_Article'));
    	
    	// Process Recordset
    	$recordset->Process();        
    }
    
    function ManageArticles_Create()
    {
        /*
         * Generate Create News Article Form
         */
        
        $form = new Form('articles_create', 'http://'.$this->GetAction('article', 'create'));
        
        // Form Actions
        $form->AddAction('save', 'Save', array(&$this, '_CreateArticle'), true);        
        $form->AddAction('preview', 'Preview', array(&$this, '_Preview'), false);        
        $form->AddAction('cancel', 'Cancel', array(&$this, 'ManageArticles_List'), false);
                
        // Form Fields
        $form->Add(new RichtextField(&$form, 'wysiwyg', 'Content'));
        $form->AddFieldSet('Summary');
        $form->Add(new TextField(&$form, 'title', 'Title', null, null, true));        
        $form->Add(new TextField(&$form, 'author', 'Author', null, $this->_User->DataObject->username, true));
        $form->Add(new SelectField(&$form, 'category', 'Category', $this->_DAL->Select('newscategory'), 'id', true, 'title'));
        $form->Add(new DateField(&$form, 'created', 'Created', null, date('Y-m-d'), true));
        $form->Add(new DateField(&$form, 'publish', 'Publish'));
        $form->Add(new DateField(&$form, 'expire', 'Expire'));
        $form->Add(new TextareaField(&$form, 'teaser', 'Teaser'));
        $form->AddFieldSet('Meta Data');
        $form->Add(new TextareaField(&$form, 'meta_keywords', 'Keywords'));
        $form->Add(new TextareaField(&$form, 'meta_description', 'Description'));
        $form->Add(new TextField(&$form, 'meta_robots', 'Robots'));
        
        // Process the form
        $form->Process();           
    }
    
    function ManageArticles_Modify()
    {
    	/*
    	 * Grab the info of the article to be modified
    	 */
    	
    	if (($article = $this->_DAL->Select('newsarticle', $_GET['aid'])) === false)
    	{
    		$this->_Model->Set('Page.Messages.Error', array('Article \''.$_GET['aid'].'\' does not exist.'));
    		$this->ManageArticles_List();
    		return false;
    	}
    	
        /*
         * Generate Modify News Article Form
         */
        
        $form = new Form('articles_modify', 'http://'.$this->GetAction('article', 'modify').'?aid='.$article->id);
        
        // Form Actions
        $form->AddAction('save', 'Save', array(&$this, '_ModifyArticle'), true);        
        $form->AddAction('preview', 'Preview', array(&$this, '_Preview'), false);        
        $form->AddAction('cancel', 'Cancel', array(&$this, 'ManageArticles_List'), false);
                
        // Form Fields
        $form->Add(new RichtextField(&$form, 'wysiwyg', 'Content', null, $article->n_body));
        $form->AddFieldSet('Summary');
        $form->Add(new TextField(&$form, 'title', 'Title', null, $article->n_title, true));        
        $form->Add(new TextField(&$form, 'author', 'Author', null, $this->_User->DataObject->username, true));
        $form->Add(new SelectField(&$form, 'category', 'Category', $this->_DAL->Select('newscategory'), 'id', true, 'title', $article->c_id));
        $form->Add(new DateField(&$form, 'created', 'Created', null, $article->n_created, true));
        $form->Add(new DateField(&$form, 'publish', 'Publish'));
        $form->Add(new DateField(&$form, 'expire', 'Expire'));
        $form->Add(new TextareaField(&$form, 'teaser', 'Teaser', null, $article->n_teaser));        
        $form->AddFieldSet('Meta Data');
        $form->Add(new TextareaField(&$form, 'meta_keywords', 'Keywords', null, $article->n_meta_keywords));
        $form->Add(new TextareaField(&$form, 'meta_description', 'Description', null, $article->n_meta_description));
        $form->Add(new TextField(&$form, 'meta_robots', 'Robots', null, $article->n_meta_robots));
        
        // Process the form
        $form->Process();            
    }
    
    function ManageArticles_Delete($selected = array())
    {
        $error   = array();
        $success = array();

        if (count($selected) > 0)
        {
	        for ($i = 0, $imax = count($selected); $i < $imax; $i++)
	        {
	            if ($this->_DAL->Delete('newsarticle', $selected[$i]) === false)
	                $error[] = $selected[$i];
	            else 
	                $success[] = $selected[$i];
	        }
	        
	        if (count($error) > 0)
	            $this->_Model->Set('Page.Messages.Error', array('Error Deleting Articles \''.implode(',', $error).'\''));
	            
	        if (count($success) > 0)
	            $this->_Model->Set('Page.Messages.Completed', array('Articles \''.implode(',', $success).'\' successfully deleted.'));
        }
        else 
        	$this->_Model->Set('Page.Messages.Information', array('One or more articles must be selected before clicking delete.'));

        	
        $this->ManageArticles_List();
    }
    
    function ManageCategories_List()
    {
    	/*
    	 * Generate List Articles Recordset
    	 */

    	$recordset = new RecordSet($this->GetAction('category'), 'articles', 'Articles [Categories]', 'newscategory');
    	
    	// Recordset Actions
    	$recordset->AddAction('create', 'Create', array(&$this, 'ManageCategories_Create'));
    	$recordset->AddAction('delete', 'Delete', array(&$this, 'ManageCategories_Delete'));    	
    	
    	// Recordset Fields
    	$recordset->AddField('id', '#', 30);
    	$recordset->AddField('title', 'Title', 100, array(&$this, '_RecordSet_Category'));    	
    	$recordset->AddField('description', 'Description');     	
    	
    	// Process Recordset
    	$recordset->Process();            
    }
    
    function ManageCategories_Create()
    {
        /*
         * Generate Create News Article Form
         */

        $form = new Form('articles_create_category', 'http://'.$this->GetAction('category', 'create'));
        
        // Form Actions
        $form->AddAction('save', 'Save', array(&$this, '_CreateCategory'), true);          
        $form->AddAction('cancel', 'Cancel', array(&$this, 'ManageCategories_List'), false);
                
        // Form Fields
        $form->AddFieldSet('Category Details');
        $form->Add(new TextField(&$form, 'title', 'Title', null, null, true));        
        $form->Add(new TextareaField(&$form, 'description', 'Description'));

        
        // Process the form
        $form->Process();          
    }
    
    function ManageCategories_Modify()
    {
    	/*
    	 * Grab the info of the article to be modified
    	 */
    	
    	if (($category = $this->_DAL->Select('newscategory', $_GET['cid'])) === false)
    	{
    		$this->_Model->Set('Page.Messages.Error', array('Category \''.$_GET['cid'].'\' does not exist.'));
    		$this->ManageCategories_List();
    		return false;
    	}
    	
        /*
         * Generate Modify News Article Form
         */
        
        $form = new Form('articles_modify_category', 'http://'.$this->GetAction('category', 'modify').'?cid='.$category->id);
        
        // Form Actions
        $form->AddAction('save', 'Save', array(&$this, '_ModifyCategory'), true);            
        $form->AddAction('cancel', 'Cancel', array(&$this, 'ManageCategories_List'), false);
                
        // Form Fields
        $form->AddFieldSet('Category Details');
        $form->Add(new TextField(&$form, 'title', 'Title', null, $category->title, true));        
        $form->Add(new TextareaField(&$form, 'description', 'Description', null, $category->description));        

        
        // Process the form
        $form->Process();            
    }
    
    function ManageCategories_Delete($selected = array())
    {
        $error   = array();
        $success = array();

        if (count($selected) > 0)
        {
	        for ($i = 0, $imax = count($selected); $i < $imax; $i++)
	        {
	            if ($this->_DAL->Delete('newscategory', $selected[$i]) === false)
	                $error[] = $selected[$i];
	            else 
	                $success[] = $selected[$i];
	        }
	        
	        if (count($error) > 0)
	            $this->_Model->Set('Page.Messages.Error', array('Error Deleting Categories \''.implode(',', $error).'\''));
	            
	        if (count($success) > 0)
	            $this->_Model->Set('Page.Messages.Completed', array('Categories \''.implode(',', $success).'\' successfully deleted.'));
        }
        else 
        	$this->_Model->Set('Page.Messages.Information', array('One or more categories must be selected before clicking delete.'));

        	
        $this->ManageCategories_List();
    }    
    
    /*
     * Private Module Methods 
     */
    
    function _CreateArticle()
    {           
        $this->_DAL->Insert('newsarticle', array('cid'                => $_POST['category'],
                                                 'n_uid'              => 1,
                                                 'n_title'            => $_POST['title'],
                                                 'n_teaser'           => $_POST['teaser'],
                                                 'n_body'             => $_POST['wysiwyg'],
                                                 'n_meta_robots'      => $_POST['meta_robots'],
                                                 'n_meta_description' => $_POST['meta_description'],
                                                 'n_meta_keywords'    => $_POST['meta_keywords'])); 
		$this->ManageArticles_List();
		$this->_Model->Set('Page.Messages.Completed', array('News Article Created'));
    }   
    
    function _ModifyArticle()
    {
    	/*
    	 * Grab a dataobject instance of the article to be modified
    	 */
    	
    	if ( !isset($_GET['aid']) || !is_numeric($_GET['aid']) || (($article = $this->_DAL->Select('newsarticle', $_GET['aid'])) === false))
    	{
    		$this->_Model->Set('Page.Messages.Error', array('Article \''.$_GET['aid'].'\' does not exist.'));
    		$this->ManageArticles_List();
    		return false;
    	}  
    	
    	/*
    	 * Modify the article
    	 */  	
    	
    	$article->cid                = $_POST['category'];
    	$article->n_uid              = 1;
    	$article->n_title            = $_POST['title'];
    	$article->n_teaser           = $_POST['teaser'];
    	$article->n_body             = $_POST['wysiwyg'];
    	$article->n_meta_robots      = $_POST['meta_robots'];
    	$article->n_meta_description = $_POST['meta_description'];
    	$article->n_meta_keywords    = $_POST['meta_keywords'];
    	
    	// Save Changes
    	$article->Save();
    	
    	$this->ManageArticles_List();
    }  
    
    function _RecordSet_Article($data)
    {
    	return '<a href="http://'.$this->GetAction('article', 'modify').'?aid='.$data['id'].'">'.$data['n_title'].'</a>';
    }
    
    function _CreateCategory()
    {
        $id = $this->_DAL->Insert('newscategory', array('title'       => $_POST['title'],
                                                        'description' => $_POST['description'])); 

        if ($id === false)                                                        
            $this->_Model->Set('Page.Messages.Completed', array('Category Creation Failed.')); 
        else
            $this->_Model->Set('Page.Messages.Completed', array('Category Created')); 
            
		$this->ManageCategories_List();		      
    }
    
    function _ModifyCategory()
    {
    	/*
    	 * Grab a dataobject instance of the category to be modified
    	 */
    	
    	if ( !isset($_GET['cid']) || !is_numeric($_GET['cid']) || (($category = $this->_DAL->Select('newscategory', $_GET['cid'])) === false))
    	{
    		$this->_Model->Set('Page.Messages.Error', array('Category \''.$_GET['cid'].'\' does not exist.'));
    		$this->ManageCategories_List();
    		return false;
    	}  
    	
    	/*
    	 * Modify the category
    	 */  	
    	
    	$category->title       = $_POST['title'];
    	$category->description = $_POST['description'];
    	
    	// Save Changes
    	$category->Save();
    	
    	$this->_Model->Set('Page.Messages.Completed', array('Category Successfully Modified.'));
    	$this->ManageCategories_List();        
    }
    
    function _RecordSet_Category($data)
    {
    	return '<a href="http://'.$this->GetAction('category', 'modify').'?cid='.$data['id'].'">'.$data['title'].'</a>';        
    }    
}

?>